<template>
  <div class="exam-status-container">
    <h2>个人考试情况</h2>

    <!-- 显示考试记录 -->
    <div v-if="examRecords.length > 0" class="exam-records">
      <table>
        <thead>
        <tr>
          <th>考试名称</th>
          <th>开始时间</th>
          <th>提交时间</th>
          <th>得分</th>
          <th>考试状态</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="record in examRecords" :key="record.id">
          <td>{{ record.exam.name }}</td>
          <td>{{ record.startTime }}</td>
          <td>{{ record.submitTime }}</td>
          <td>{{ record.score }}</td>
          <td>{{ record.isSubmitted ? '已提交' : '未提交' }}</td>
        </tr>
        </tbody>
      </table>
    </div>
    <div v-else>
      <p>没有考试记录。</p>
    </div>

    <!-- 下载报表按钮 -->
    <el-button type="primary" @click="downloadReport">下载考试报表</el-button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from '@/utiles/axios';

const studentId = localStorage.getItem('studentId');
const examRecords = ref([]);

const fetchExamRecords = async () => {
  try {
    const response = await axios.get(`/student/exam-records/${studentId}`);
    examRecords.value = response.data;
  } catch (error) {
    console.error('获取考试记录失败', error);
  }
};

const downloadReport = async () => {
  try {
    const response = await axios.get(`/student/exam-report/${studentId}`, { responseType: 'blob' });
    const blob = new Blob([response.data], { type: 'application/pdf' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'exam_report.pdf';
    link.click();
  } catch (error) {
    console.error('下载报表失败', error);
  }
};

onMounted(() => {
  fetchExamRecords();
});
</script>

<style scoped>
.exam-status-container {
  max-width: 800px;
  margin: 50px auto;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  font-size: 2em;
  color: #333;
}

.exam-records table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.exam-records th,
.exam-records td {
  padding: 10px;
  border: 1px solid #ddd;
  text-align: center;
}

.exam-records th {
  background-color: #f4f4f4;
}

.el-button {
  display: block;
  width: 100%;
  margin-top: 30px;
}
</style>
